#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Tubemaster
#
# Copyright (C) 2009 Selim Ok <selimok@gmail.com>
# Copyright (C) 2007-2008 Siegfried-Angel Gevatter Pujals <siggi.gevatter@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

import sys
import os
import time
import re

try:
	from PyQt4 import QtCore, QtGui, QtNetwork
except ImportError:
	print '\nTubemaster Error!'
	print '\n'
	print 'Dependency Problem - The required PyQt4 libraries couldn\'t be found.\n'
	exit()

# Import needed modules provided by Tubemaster itself
import preferences, notifications, constants, converter

# Import needed GUI classes
from ui_main import Ui_MainWindow

# Localize the application
#locale = str(QtCore.QLocale.system().name())
#translator = QtCore.QTranslator()
#translator.load('../data/lang/' + locale)

class Gui(QtGui.QMainWindow):
	"""main class."""
	
	def __init__(self, sysarg1='', parent=None):
		"""Initialize the GUI and many variables and load the configuration."""
		
		QtGui.QWidget.__init__(self, parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		
		# Load configuration
		self.settings = preferences.loadSettings()
		self.ui.dest_folder.setText(self.settings.value('General/folder').toString())
		self.prevConfig = {
			'folder':self.settings.value('General/folder').toString(),
		}
		
		# Initialize modules
		self.notification = notifications.Notification(self.settings, 'Tubemaster')
				
		# Initialize variables
		self.dialogs = {
				'about': None,		# The instance of the "About..." window will be stored here
				'preferences':None,	# The instance of the "Preferences" window will be stored here
			}
		self.videoInput = {
				'wasUrl':None,		# The value videoUrl had last time self.() was called
				'wasId':None,		# The value videoId had last time it changed
				'fromUrl':None,		# Wheter there was an Id in videoUrl or not last time self.urlChange() was called
			}
		self.download = None		# Holds the QHttp object
		self.downloadUrl = None		# The url of the video that's currently being downloaded
		self.isMinimal = None		# Whether the window is in "minimal" mode or not
		self.threadUrl = None		# The thread that gets the download url from youtube-dl
                self.orgTitle = None		# The thread that gets the original title from youtube-dl
                self.quality = 'good'           # The default quality parameter of the videos
		self.format = 'mp3'             # The default file format of the videos

                self.format_set = set(['mp3','flv','avi','mp4'])
                self.format_picker = {0:'mp3',1:'flv',2:'avi',3:'mp4'}
                self.quality_picker = {0:'high',1:'good',2:'normal',3:'low'}
                self.qtof_converter = {'high':'flv','good':'mp4','normal':'flv','low':'3gp'}

		# Get the sizes for the «minimal» and the «expanded» views of the main window
		self.size = {
				'width':{ 'min': self.minimumWidth(), 'max': self.maximumWidth() },
				'height':{ 'min': self.minimumHeight(), 'max': self.maximumHeight() },
			}
		
		self.urlInputWidth = self.ui.videoUrl.width()
		
		# Apply the sizes of the «minimal» view to the window and setup a timer, if needed
		if self.settings.value('Interface/startMinimal').toBool():
			self.isMinimal = True
			self.setFixedSize(QtCore.QSize(QtCore.QRect(0, 0, self.size['width']['min'], self.size['height']['min']).size()))
			if self.settings.value('Interface/effectExpand').toBool():
				self.timerExpand = QtCore.QTimer()
				QtCore.QObject.connect(self.timerExpand, QtCore.SIGNAL("timeout()"), self.expandViewSlow);
		
		# Adjust the inputs to fit the current configuration
		self.adjustInputs()
		
		# Connect signals with slots
		QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.close)
		QtCore.QObject.connect(self.ui.actionPreferences, QtCore.SIGNAL("triggered()"), self.showPreferences)
		QtCore.QObject.connect(self.ui.actionAbout, QtCore.SIGNAL("triggered()"), self.showAbout)
		
		QtCore.QObject.connect(self.ui.button_folder, QtCore.SIGNAL("clicked()"), self.browseFolder)
		QtCore.QObject.connect(self.ui.button_get, QtCore.SIGNAL("clicked()"), self.getVideo)
		QtCore.QObject.connect(self.ui.button_get, QtCore.SIGNAL("clicked()"), self.appendExtention)
                QtCore.QObject.connect(self.ui.button_abort, QtCore.SIGNAL("clicked()"), self.downloadAbort)
		QtCore.QObject.connect(self.ui.button_pause, QtCore.SIGNAL("clicked()"), self.downloadPause)
		QtCore.QObject.connect(self.ui.button_resume, QtCore.SIGNAL("clicked()"), self.downloadResume)
		QtCore.QObject.connect(self.ui.button_gettitle, QtCore.SIGNAL("clicked()"), self.getTitle)

		QtCore.QObject.connect(self.ui.videoId, QtCore.SIGNAL("textChanged(QString)"), self.idChange)
		QtCore.QObject.connect(self.ui.videoId, QtCore.SIGNAL("returnPressed()"), self.getVideo)
		QtCore.QObject.connect(self.ui.videoUrl, QtCore.SIGNAL("textChanged(QString)"), self.urlChange)
		QtCore.QObject.connect(self.ui.videoUrl, QtCore.SIGNAL("returnPressed()"), self.getVideo)
		QtCore.QObject.connect(self.ui.dest_name, QtCore.SIGNAL("returnPressed()"), self.getVideo)
                #QtCore.QObject.connect(self.ui.dest_name, QtCore.SIGNAL("textChanged(QString)"), self.updateTitleStatus)
		QtCore.QObject.connect(self.ui.dest_quality, QtCore.SIGNAL("currentIndexChanged(int)"), self.setQuality)	
		QtCore.QObject.connect(self.ui.dest_format, QtCore.SIGNAL("currentIndexChanged(int)"), self.setFormat)

                # Hide pause-resume buttons
                self.ui.stackPause.hide()

                # Set default status message
                self.setDefaultStatus()

		# If the application was called with a argument, and it is a URL, put it into videoUrl
		if sysarg1 is not '' and sysarg1[:7] == 'http://':
                        self.ui.videoUrl.setStyleSheet("QLineEdit { color: #000000 }")
			self.ui.videoUrl.setText(sysarg1)
	
	def adjustInputs(self, updatedSettings=False):
		"""Changes the input's visibility and size, if required by some setting."""
		
		if self.settings.value('General/onlyUrl').toBool():
			self.ui.videoId.setVisible(False)
			self.ui.videoUrl.setFixedWidth( self.ui.videoUrl.width() + self.ui.videoId.width() + (self.ui.videoId.x() - (self.ui.videoUrl.x() + self.ui.videoUrl.width())) )
		elif updatedSettings:
			self.ui.videoUrl.setFixedWidth(self.urlInputWidth)
			self.ui.videoId.setVisible(True)
		
		if updatedSettings:
			if self.ui.dest_folder.text() == self.prevConfig['folder']:
				self.ui.dest_folder.setText(self.settings.value('General/Folder').toString())

        def setFileName(self,name):
            self.ui.dest_name.setText(QtCore.QString(str(name).decode("utf-8")))

        def getFileName(self):
            return str(self.ui.dest_name.text())

        def getDestDir(self):
            return str(self.ui.dest_folder.text())

        def enableGettitle(self):
            self.ui.button_gettitle.setEnabled(True)
            self.ui.stackPause.show()
            self.ui.stackPause.setCurrentIndex(2)
#            self.setStatus('Ready to \"Get Original Title\" or \"Download Video\" with a custom title!')

        def disableGettitle(self):
            self.ui.button_gettitle.setEnabled(False)

        def hideGettitle(self):
            self.disableGettitle()
            self.ui.stackPause.hide()

        def updateVideoUrl(self):
            #Update URL via write prefix of YouTube and append the Video ID on its tail
            videoId=self.ui.videoId.text()
            videoUrl=self.ui.videoUrl.text()
            if videoUrl=='' or videoUrl==constants.youtube_prefix or videoId!=videoUrl[len(constants.youtube_prefix):] :
                text=constants.youtube_prefix+videoId
                self.ui.videoUrl.setText(QtCore.QString(str(text).decode("utf-8")))

        def setFormat(self):
            self.format = self.format_picker[self.ui.dest_format.currentIndex()]
            self.updateExtention()

        def setQuality(self):
            self.quality = self.quality_picker[self.ui.dest_quality.currentIndex()]

        def setStatus(self,text):
            self.ui.status_text.setStyleSheet("color: #00C21D")
            self.ui.status_text.setText(QtCore.QString(str(text).decode("utf-8")))

        def setErrorStatus(self,text):
            self.ui.status_text.setStyleSheet("color: #FF0000")
            self.ui.status_text.setText(QtCore.QString(str(text).decode("utf-8")))

        def setInfoStatus(self,text):
            self.ui.status_text.setStyleSheet("color: #FF9500")
            self.ui.status_text.setText(QtCore.QString(str(text).decode("utf-8")))

        def setDefaultStatus(self):
            self.ui.status_text.setStyleSheet("color: #000000")
            self.ui.status_text.setText(QtCore.QString(str('Write the location or ID of the video you want to get above and press "Get Video".').decode("utf-8")))

        def replaceSpaces(self):
            if self.settings.value('General/spaces').toBool():
                self.setFileName(str(self.ui.dest_name.text()).replace(' ','_'))

	def cleanSpecialChars(self,text):
	    cleantext=""
	    text = unicode(text)
	    for index in range(len(text)):
		if re.search(u"ş",text[index]):
		    cleantext=cleantext+"s"
		elif re.search(u"ı",text[index]):
		    cleantext=cleantext+"i"
		elif re.search(u"ç",text[index]):
		    cleantext=cleantext+"c"
		elif re.search(u"ü",text[index]):
		    cleantext=cleantext+"u"
		elif re.search(u"ö",text[index]):
		    cleantext=cleantext+"o"
		elif re.search(u"ğ",text[index]):
		    cleantext=cleantext+"g"
		elif re.search(u"Ş",text[index]):
		    cleantext=cleantext+"S"
		elif re.search(u"I",text[index]):
		    cleantext=cleantext+"I"
		elif re.search(u"Ç",text[index]):
		    cleantext=cleantext+"C"
		elif re.search(u"Ü",text[index]):
		    cleantext=cleantext+"u"
		elif re.search(u"Ö",text[index]):
		    cleantext=cleantext+"O"
		elif re.search(u"Ğ",text[index]):
		    cleantext=cleantext+"G"
		elif re.search(u"ß",text[index]):
		    cleantext=cleantext+"ss"
		elif re.search(u"ä",text[index]):
		    cleantext=cleantext+"ae"
		elif re.search("([A-Z]|[a-z]|[0-9]|-|_|[\s]|[:blank:]|[:space:])",text[index]):
		    cleantext=cleantext+text[index]
	    return cleantext

        def getTitle(self):

            if self.ui.button_gettitle.isEnabled() is not True:
                return 0
            
            # Update Video URL(only if it's empty) according to the VideoID
            self.updateVideoUrl()

            self.disableGettitle()
            self.setInfoStatus('Please wait, fetching original title of video...')

            from getoriginaltitle import GetOriginalTitle
            self.orgTitle = GetOriginalTitle(str(self.ui.videoId.text()), self.settings.value('General/script').toString())
            self.orgTitle.start()

            self.timerThreadTitle = QtCore.QTimer()
            QtCore.QObject.connect(self.timerThreadTitle, QtCore.SIGNAL("timeout()"), self.isTitleReady);
            self.timerThreadTitle.start(750);
	
        def isTitleReady(self):
            """Checks if the `youtube-dl` thread is read and, if it is set the filename."""

            if self.orgTitle.result is not None:
                self.timerThreadTitle.stop()
                if len(str(self.orgTitle.result))==0:
                    self.setErrorStatus('Can\'t get the original title, check your internet connection or the URL.')
                    self.enableGettitle()
                else:
                    self.setFileName(self.cleanSpecialChars(self.orgTitle.result))
                    self.appendExtention()
                    self.replaceSpaces()
                    self.enableGettitle()
                    self.setStatus('Ready to download with original title!')
            elif (not self.timerThreadTitle.isActive()):
                self.setErrorStatus('Can\'t get the original title due to timeout, check your internet connection.')
                self.enableGettitle()

	def expandView(self):
		"""Expand the window, to show the «Progress» section too. If needed, calls expandViewSlow()."""
		
		if self.settings.value('Interface/effectExpand').toBool():
			self.timerExpand.start(7)
		else:
			self.setFixedSize(QtCore.QSize(QtCore.QRect(0, 0, self.size['width']['min'], self.size['height']['max']).size()))
		
		
	def expandViewSlow(self):
		"""Nice effect that slowly expands the window."""
		
		if self.height() < self.size['height']['max']:
			if (self.height() + 3) <= self.size['height']['max']:
				self.setFixedSize(QtCore.QSize(QtCore.QRect(0, 0, self.size['width']['min'], self.height() + 3).size()))
			else:
				self.setFixedSize(QtCore.QSize(QtCore.QRect(0, 0, self.size['width']['min'], self.size['height']['max']).size()))
		
		else:
			self.timerExpand.stop()
			self.isMinimal = None
		
	def idChange(self):
		"""Handles text changes in videoId."""
		
		self.ui.videoId.setText(''.join(str(self.ui.videoId.text().toAscii()).split(' ')))
		
		videoId = self.ui.videoId.text()
		
		if self.ui.videoUrl.text() == '' and (videoId[0:7] == 'http://' or videoId[0:4] == 'www.'):
			# If a URL is written in the Id field, move it to the correct one.
			self.ui.videoId.setText('')
			self.ui.videoUrl.setText(videoId)
			self.ui.videoUrl.setFocus()
			return True
		
		if videoId != '':
			self.ui.button_get.setEnabled(True)
			self.enableGettitle()

			if  os.path.splitext(str(self.ui.dest_name.text()))[0] == str(self.videoInput['wasId']) or self.ui.dest_name.text() == '':
                                self.setFileName(videoId + '.' + self.format)
			
		else:
			self.ui.button_get.setEnabled(False)
                        self.setDefaultStatus()
                        self.hideGettitle()
			
			if os.path.splitext(str(self.ui.dest_name.text()))[0] == str(self.videoInput['wasId']):
                                self.setFileName('')
		
		self.videoInput['wasId'] = videoId
                
	def urlChange(self):
		""""Handles text changes in videoUrl."""
		
		# Automagically fix errors
		if self.ui.videoUrl.text()[0:4] == 'www.':
			self.ui.videoUrl.setText('http://' + self.ui.videoUrl.text())
		
		self.ui.videoUrl.setText(''.join(str(self.ui.videoUrl.text().toAscii()).split(' ')))
		
		# Only continue if the URL seems valid
		if self.ui.videoUrl.text() != '' and self.ui.videoUrl.text()[0:7] != 'http://':
			if not self.ui.videoId.isEnabled():
				self.ui.videoId.setText('')
                                self.setDefaultStatus()
				self.ui.videoId.setEnabled(True)
			return 0
		
		try:
			self.ui.videoId.setText( 
				str(self.ui.videoUrl.text())[(str(self.ui.videoUrl.text()).index("v=") + 2):] )
			fromUrl = True
			try:
				self.ui.videoId.setText(str(self.ui.videoId.text())[:str(self.ui.videoId.text()).index("&")] )
			except ValueError:
				pass
		except ValueError:
			fromUrl = False
		
		if self.videoInput['fromUrl'] and not fromUrl:
			self.ui.videoId.setText('')
                        self.setDefaultStatus()
		
		if self.ui.videoUrl.text() == '' and self.videoInput['wasUrl']:
			self.ui.videoId.setText('')
                        self.setDefaultStatus()
			self.videoInput['wasUrl'] = False
			
		if self.ui.videoUrl.text() and self.ui.videoId.text():
			self.ui.videoId.setEnabled(False)
			self.ui.button_get.setEnabled(True)
                        self.enableGettitle()
		elif self.ui.videoId.text() == '':
			self.ui.videoId.setEnabled(True)
			self.ui.button_get.setEnabled(False)
                        self.hideGettitle()
		
		if self.ui.videoId.text() != '' and ( os.path.splitext(str(self.ui.dest_name.text()))[0] == str(self.videoInput['wasId']) or self.ui.dest_name.text() == '' ):
                        self.setFileName(self.ui.videoId.text() + '.' + self.format)
		elif self.ui.videoId.text() == '' and os.path.splitext(str(self.ui.dest_name.text()))[0] == str(self.videoInput['wasId']):
                        self.setFileName('')
		
		self.videoInput['fromUrl'] = fromUrl
		self.videoInput['wasUrl'] = self.ui.videoUrl.text()
		self.videoInput['wasId'] = self.ui.videoId.text()
		
	def appendExtention(self):
		"""Handles changes in the name of the destination file."""
		
		# Add the extension, if it gets removed
		if self.ui.dest_name.text() != '' and not (str(self.ui.dest_name.text())[-3:] in self.format_set):
                    while self.ui.dest_name.text()[-1:] == '.':
                        # Delete points from the end ('filename..extension' looks ugly)
                            self.setFileName(self.ui.dest_name.text()[:-1])
                    self.setFileName(self.ui.dest_name.text() + '.' + self.format)

	def updateExtention(self):
            """Handles changes in the name of the destination file."""

            # Update the extension, if it gets changed
            if str(self.ui.dest_name.text())[-3:] != self.format:
                # if already an extention exist
                if self.ui.dest_name.text()[-4:-3] == '.':
                    self.setFileName(self.ui.dest_name.text()[:-4] + '.' + self.format)
                else:
                    self.setFileName(self.ui.dest_name.text() + '.' + self.format)
		
	def browseFolder(self):
		"""Shows a folder selection dialog and (if the user doesn't cancel it) sets the new destination in the input."""
		
		dest_folder = preferences.selectFolder(self, self.ui.dest_folder.text())
		
		if dest_folder:
			self.ui.dest_folder.setText(dest_folder)
		
	def getVideo(self):
		"""Starts a thread to youtube-dl, retrieves the download url, and does all other stuff needed to get the video."""
		
		if self.ui.button_get.isEnabled() is not True:
			return 0
		
		# Reset the data in «Progress»
		self.setStatus('')
		self.ui.progressBar.setValue(0)

                # Append format extention if required
                self.appendExtention()

                # Update Video URL(only if it's empty) according to the VideoID
                self.updateVideoUrl()

                # Create the file-object where the video will be saved
                from os.path import join
                self.filename = os.path.join(str(self.ui.dest_folder.text()), str(self.ui.dest_name.text()))

                # TODO: Ask to continue an old download, if found (?).

                if len(self.ui.dest_name.text())>0:
                    if os.path.exists(self.filename):
                        overwrite = QtGui.QMessageBox.warning(self, 
                            self.tr("Tubemaster - Overwrite File?"),
                            self.tr("There is already a file with this name. Are you sure you want to overwrite it?"),
                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.Abort,
                            QtGui.QMessageBox.Abort,
                        );
                        if overwrite == QtGui.QMessageBox.Abort:
                            return 0
                else:
                    self.setErrorStatus('Filename can\'t be empty!')
                    return 0


                # Block all possible value changes by the user
                self.inputsEnable(False)

                self.setInfoStatus(self.tr('Retrieving video URL...'))
                self.ui.button_abort.setEnabled(False)
                self.ui.button_gettitle.setEnabled(False)

                from getdownloadurl import GetDownloadUrl
                self.downloadUrl = GetDownloadUrl(str(self.ui.videoId.text()), self.quality, self.settings.value('General/script').toString())
                self.downloadUrl.start()

                self.timerThreadUrl = QtCore.QTimer()
                QtCore.QObject.connect(self.timerThreadUrl, QtCore.SIGNAL("timeout()"), self.isDownloadReady);
                self.timerThreadUrl.start(750);



        def isDownloadReady(self):
            """Checks if the `youtube-dl` thread is read and, if it is, calls download()."""
            if self.downloadUrl.result is not None:
                self.timerThreadUrl.stop()
                if len(str(self.downloadUrl.result))==0:
                    self.setErrorStatus('Can\'t get the download url, check your internet connection or the URL.')
                    self.beep()
                    self.inputsEnable(True)
                    self.ui.button_abort.setEnabled(True)
                    self.ui.button_gettitle.setEnabled(True)
                else:
                    self.inputsEnable(False)
                    self.downloadStart(self.downloadUrl.result)
            elif (not self.timerThreadUrl.isActive()):
                self.setErrorStatus('Can\'t get the download url due to timeout, check your internet connection.')
                self.beep()
                self.inputsEnable(True)
                self.ui.button_get.setEnabled(True)

	def inputsEnable(self, enabled=True):
		"""Massively enables or disables all inputs and changes which buttons that are enabled or even visible."""
		
		self.ui.videoUrl.setEnabled(enabled)
		self.ui.videoId.setEnabled(enabled)
		self.ui.dest_folder.setEnabled(enabled)
		self.ui.button_folder.setEnabled(enabled)
		self.ui.dest_name.setEnabled(enabled)
		self.ui.dest_format.setEnabled(enabled)
                self.ui.dest_quality.setEnabled(enabled)

		if enabled is True:
			self.ui.stackButtons.setCurrentWidget(self.ui.p_get)
			self.urlChange()
		else:
			self.ui.stackButtons.setCurrentWidget(self.ui.p_abort)
		
	def getHeaderContinue(self, startFrom, totalSize):
		"""Returns a QHttpRequestHeader object that tells the server to continue a incomplete download."""
		"""
		headers = QtNetwork.QHttpRequestHeader()	# Continue a paused or aborted download
		request = "GET /d1/06/98/JAtzHFvAWu0.flv HTTP/1.1\r\n"
		request += "Connection: Keep-Alive\r\n"
		# request += "Host: youtube-820.vo.llnwd.net\r\n"
		request += "Content-Range: bytes " + str(startFrom) + "-" + str(totalSize - 1) + "/" + str(totalSize) + "\r\n"	# TODO!
		request += "Content-Lenght: " + str(startFrom) + "\r\n"
		print request
		headers.setRequest(request, self.downloadUrl[1])
		
		return headers
		"""
		pass
		
	def downloadStart(self, result):
		"""Gets the resulting output from `youtube-dl` and handles it."""
                self.downloadUrl = result
                self.filename = self.getFileName()
                self.destdir = self.getDestDir()

		# Change the status messages
		self.setStatus('Starting to download...')

                self.ui.button_abort.setEnabled(True)

		# Expand the window, if needed
		if self.isMinimal is not None:
			self.expandView()
		
		# Display the pause button
                # self.ui.stackPause.show()
		# self.ui.stackPause.setCurrentIndex(0)
		
		# Start downloading the video
                import fetcher
                self.Download = fetcher.Fetcher(self.downloadUrl, self.destdir, self.filename)
                self.Download.start()

                self.timerDownload = QtCore.QTimer()
                QtCore.QObject.connect(self.timerDownload, QtCore.SIGNAL("timeout()"), self.checkDownloadStatus)
                self.timerDownload.start(750)


        def checkDownloadStatus(self):
            if self.Download.error is not None:
                self.timerDownload.stop()
                self.setErrorStatus(self.Download.error)
                self.beep()
                #self.notification.showNotification('Download Failed', 'Sorry, the download of video "' + self.Download.filename + '" has failed.', category='transfer.error')
                self.ui.stackPause.setCurrentIndex(2)
                self.inputsEnable(True)
            elif self.Download.getPercent() == 100:
                self.timerDownload.stop()
                self.setProgress(self.Download.getPercent(),self.Download.getSpeed(),self.Download.getEta())
                self.setInfoStatus('Download succesfully completed! Please wait while post processing...')
                self.postProcess()
                #self.notification.showNotification('Video Downloaded', 'Video downloaded successfully from YouTube and saved as "' + filename + '".', category='transfer.complete')
            else:
                self.setInfoStatus('Please wait while downloading file...')
                self.setProgress(self.Download.getPercent(),self.Download.getSpeed(),self.Download.getEta())

        def setProgress(self,percent,speed,eta):
            self.ui.progressBar.setValue(percent)
            self.ui.progressLabel.setText('Speed: %s / ETA: %s ' %(speed,eta))

        def postProcess(self):
            self.ui.button_abort.setEnabled(False)
            self.convertVideo()
            # All operations completed,enable gui elements
            self.ui.button_abort.setEnabled(True)
            self.ui.stackPause.setCurrentIndex(2)
            self.inputsEnable(True)

        def convertVideo(self):
            from converter import Converter
            self.convert = Converter(self.destdir, self.filename)
            self.convert.start()

            self.timerConverter = QtCore.QTimer()
            QtCore.QObject.connect(self.timerConverter, QtCore.SIGNAL("timeout()"), self.isConvertingDone);
            self.timerConverter.start(750);

        def isConvertingDone(self):
            if self.convert.error is not None:
                self.timerConverter.stop()
                if self.convert.error == 0:
                    self.setStatus('All operations succesfully completed!')
                else:
                    self.setErrorStatus(self.convert.error)

	def downloadPause(self):
            pass

        def downloadResume(self):
            pass

	def downloadDone(self, errors):
            pass

	def downloadAbort(self):
            """Aborts the current download, if any."""
            try:
                self.timerDownload.stop()
            except:
                pass

            try:
                self.Download.stop()
            except:
                pass

            self.setInfoStatus('You have aborted the download.')
            self.ui.progressBar.setValue(0)
            self.ui.progressLabel.setText('')
            self.ui.stackPause.setCurrentIndex(2)
            self.inputsEnable(True)

        def beep(self):
            """If the user has "Beep on error" enabled, a beep sound will be produced"""
            if self.settings.value('Interface/beep').toBool():
                print '\a'

	def showAbout(self):
		"""Displays the 'About...' dialog."""
		
		if self.dialogs['about'] is None:
			from ui_about import Ui_AboutWindow
			self.dialogs['about'] = QtGui.QDialog()
			self.dialogs['about'].ui = Ui_AboutWindow()
			self.dialogs['about'].ui.setupUi(self.dialogs['about'])
		
		self.dialogs['about'].show()
		self.dialogs['about'].activateWindow()
		
	def showPreferences(self):
		"""Displays the 'Preferences...' dialog."""
		
		if self.dialogs['preferences'] is None:
			self.dialogs['preferences'] = preferences.PreferencesGui(self, self.settings)
		
		self.dialogs['preferences'].show()
		self.dialogs['preferences'].activateWindow()
		
	def closeEvent(self, e):
		"""This function is called when the application is closed using one of the features that the window manager offers."""
		self.close()
		
	def close(self):
		"""Expands QMainWindow's close function, in order to add other stuff that has to be done before the program ends."""
		
		self.downloadAbort()
		
		if self.dialogs['about'] is not None:
			self.dialogs['about'].done(1)
		
		for instance in self.notification.getNotifications():
			instance.close()
		
		QtGui.QMainWindow.close(self)

if __name__ == "__main__":
	
        script_dir = os.path.join(os.getcwd(),os.path.dirname(sys.argv[0]))
        os.chdir(script_dir)

	if (len(sys.argv) > 1) and (sys.argv[1] == '--version' or sys.argv[1] == '-v'):
		print 'Tubemaster Version 0.2 alpha'
		exit()
	
	app = QtGui.QApplication(sys.argv)
#        app.installTranslator(translator)

	try:
		mainApp = Gui(sys.argv[1])
	except IndexError:
		mainApp = Gui()
	
	mainApp.show()
	
	try:
		app.exec_()
	except KeyboardInterrupt:
		sys.exit()
